package com.dotstone.chipism.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Order;
import com.dotstone.chipism.bean.Region;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.timepicker.AbstractWheelTextAdapter;
import com.dotstone.chipism.timepicker.OnWheelChangedListener;
import com.dotstone.chipism.timepicker.OnWheelScrollListener;
import com.dotstone.chipism.timepicker.WheelView;
import com.dotstone.chipism.ui.login.LoginActivity;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.BlurBehind;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBlurCompleteListener;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class PublishOrderActivity extends BaseActivity {
	private TextView tv_statusBar_mian;
	private LinearLayout mBackL;
	private Button mPublishB;
	private EditText mAddressEd;
	private EditText mContactEd;
	private EditText mContactEd1;
	private TextView mTimeT;
	private LinearLayout mTimeL;
	private long timeStemp;
	private NormalDialog mNormalDialog;
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private TextView mDescriptionTv;
	private TextView mAddrTv;
	// private String tel;
	private Dialog dialog;
	private WheelView mProLv;
	private WheelView mCityLv;
	private WheelView mDistLv;
	private ArrayList<Region> provinces = new ArrayList<Region>();
	private ArrayList<Region> cities = new ArrayList<Region>();
	private ArrayList<Region> districts = new ArrayList<Region>();
	private AddressTextAdapter mProvinceAdapter;
	private AddressTextAdapter mCityAdapter;
	private AddressTextAdapter mDistrictAdapter;
	private String province;
	private String city;
	private String district;
	private TextView provinceTv;
	private TextView cityTv;
	private TextView districtTv;
	private Button mOkB;
	private int maxTextSize = 18;
	private int minTextSize = 16;
	private int currentProvinceIndex = 0;
	private int currentCityIndex = 0;
	private int currentDistrictIndex = 0;
	private EditText dingdanhao_ed;
	private SVProgressHUD mSvprogressbar;
	private String number;
	private String region;
	private String address;
	private String name;
	private String phone;
	private String date;
	private String explain;
	private String year;
	private String month;
	private String day;
	private String hour;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			// finish();
			confirm();
			break;
		case R.id.time_l:
			BlurBehind.getInstance().execute(PublishOrderActivity.this, new OnBlurCompleteListener() {
				@Override
				public void onBlurComplete() {
					Intent intent = new Intent(PublishOrderActivity.this, TimeSettingActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
					startActivityForResult(intent, 0);
				}
			});
			break;
		case R.id.public_b:
			// 检查地址是否为空
			number = dingdanhao_ed.getText().toString();
			region = mAddrTv.getText().toString();
			address = mAddressEd.getText().toString();
			name = mContactEd.getText().toString();
			phone = mContactEd1.getText().toString();
			date = mTimeT.getText().toString();
			explain = mDescriptionTv.getText().toString();
			if (number.isEmpty()) {
				ToastShow.Show(getApplicationContext(), getString(R.string.dingdan_not_null));
				return;
			}
			if (region.isEmpty()) {
				ToastShow.Show(getApplicationContext(), getString(R.string.area_not_null));
				return;
			}
			if (address.isEmpty()) {
				ToastShow.Show(getApplicationContext(), getString(R.string.address_not_null));
				return;
			}
			if (name.isEmpty()) {
				ToastShow.Show(getApplicationContext(), getString(R.string.nameconnotnull));
				return;
			}
			if (phone.isEmpty()) {
				ToastShow.Show(getApplicationContext(), getString(R.string.phoneconnotnull));
				return;
			}
			if (phone.length() != 11) {
				ToastShow.Show(getApplicationContext(), getString(R.string.phone_not_right));
				return;
			}
			if (date.isEmpty()) {
				ToastShow.Show(getApplicationContext(), getString(R.string.dateconnotnull));
				return;
			}
			// 发布工单
			mSvprogressbar.showWithStatus("正在提交");
			if (DeviceManager.getInstance().getCurrentOrder().getPublishUserName() == null) {
				publishOrder(number, region, address, date, name, phone, explain);
			} else {
				cancelOrder();
			}
			break;
		case R.id.address_tv:
			// initDialog();
			initDialog2();
			break;
		default:
			break;
		}
	}

	@SuppressWarnings("deprecation")
	private void initDialog2() {
		dialog = new Dialog(PublishOrderActivity.this, R.style.MyDialogStyle);
		dialog.setContentView(R.layout.dialog_address_selection1);
		Window dialogWindow = dialog.getWindow();
		mProvinceAdapter = new AddressTextAdapter(PublishOrderActivity.this, provinces, 0, maxTextSize, minTextSize);
		mCityAdapter = new AddressTextAdapter(PublishOrderActivity.this, cities, 0, maxTextSize, minTextSize);
		mDistrictAdapter = new AddressTextAdapter(PublishOrderActivity.this, districts, 0, maxTextSize, minTextSize);
		mProLv = (WheelView) dialog.findViewById(R.id.province_listview);
		mCityLv = (WheelView) dialog.findViewById(R.id.city_listview);
		mDistLv = (WheelView) dialog.findViewById(R.id.district_listview);
		provinceTv = (TextView) dialog.findViewById(R.id.province);
		cityTv = (TextView) dialog.findViewById(R.id.city);
		districtTv = (TextView) dialog.findViewById(R.id.district);
		mOkB = (Button) dialog.findViewById(R.id.ok);
		mOkB.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mAddrTv.setText(province + "" + city + "" + district + "");
				dialog.dismiss();
			}
		});
		mProLv.setViewAdapter(mProvinceAdapter);
		mProLv.setVisibleItems(4);
		mProLv.setCurrentItem(currentProvinceIndex);
		mCityLv.setVisibleItems(4);
		mCityLv.setViewAdapter(mCityAdapter);
		mCityLv.setCurrentItem(currentCityIndex);
		mDistLv.setVisibleItems(4);
		mDistLv.setViewAdapter(mDistrictAdapter);
		mDistLv.setCurrentItem(currentDistrictIndex);
		setTextviewSize(provinces.get(0).getName(), mProvinceAdapter);
		setTextviewSize(cities.get(0).getName(), mCityAdapter);
		setTextviewSize(districts.get(0).getName(), mDistrictAdapter);
		province = provinces.get(0).getName();
		city = cities.get(0).getName();
		district = districts.get(0).getName();
		provinceTv.setText(provinces.get(0).getName());
		cityTv.setText(cities.get(0).getName());
		districtTv.setText(districts.get(0).getName());
		mProLv.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				// Log.i("wmy", "oldValue = " + oldValue + " newValue = " +
				// newValue + " "
				// + provinces.get(newValue).getFullName());
				setTextviewSize(provinces.get(newValue).getName(), mProvinceAdapter);
				currentProvinceIndex = newValue;
			}
		});
		mProLv.addScrollingListener(new OnWheelScrollListener() {

			@Override
			public void onScrollingStarted(WheelView wheel) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScrollingFinished(WheelView wheel) {
				// TODO Auto-generated method stub
				String currentText = (String) mProvinceAdapter.getItemText(wheel.getCurrentItem());
				province = currentText;
				provinceTv.setText(province);
				Log.i("wmy", "滚动停止" + currentProvinceIndex);
				getCity(provinces.get(currentProvinceIndex).getCode());
			}
		});
		mCityLv.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				currentCityIndex = newValue;
				setTextviewSize(cities.get(newValue).getName(), mCityAdapter);
			}
		});
		mCityLv.addScrollingListener(new OnWheelScrollListener() {

			@Override
			public void onScrollingStarted(WheelView wheel) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScrollingFinished(WheelView wheel) {
				// TODO Auto-generated method stub
				String currentText = (String) mCityAdapter.getItemText(wheel.getCurrentItem());
				city = currentText;
				cityTv.setText(city);
				Log.i("wmy", "滚动停止" + currentCityIndex);
				getDistricts(cities.get(currentCityIndex).getCode());
			}
		});
		mDistLv.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				currentDistrictIndex = newValue;
				setTextviewSize(districts.get(newValue).getName(), mDistrictAdapter);
			}
		});
		mDistLv.addScrollingListener(new OnWheelScrollListener() {

			@Override
			public void onScrollingStarted(WheelView wheel) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScrollingFinished(WheelView wheel) {
				// TODO Auto-generated method stub
				String currentText = (String) mDistrictAdapter.getItemText(wheel.getCurrentItem());
				district = currentText;
				districtTv.setText(district);
				Log.i("wmy", "滚动停止" + currentDistrictIndex);
			}
		});
		LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.CENTER);
		lp.width = LayoutParams.FILL_PARENT;
		dialogWindow.setAttributes(lp);
		dialog.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			confirm();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void confirm() {
		mNormalDialog = new NormalDialog(PublishOrderActivity.this);
		mNormalDialog.content("是否取消安装工单的发布？").style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}
		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				finish();
			}

		});
	}

	private void cancelOrder() {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				ToastShow.Show(getApplicationContext(), "没有网络");
				if (mSvprogressbar.isShowing()) {
					mSvprogressbar.dismiss();
				}
				return;
			}
			RequestParams params = new RequestParams(HttpURL.REVOKE_ORDER_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("handlType", "2");
				obj.put("id", DeviceManager.getInstance().getCurrentOrder().getId());
				obj.put("key", "10000");
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
				obj.put("score", "0");
				Log.d("test", " cancel order = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("wmy", "cancel order =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							Order order = new Order();
							DeviceManager.getInstance().setCurrentOrder(order);
							publishOrder(number, region, address, date, name, phone, explain);
						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							Toast.makeText(getApplicationContext(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
							startActivity(new Intent(getApplicationContext(), LoginActivity.class));
							finish();
						} else {
							if (mSvprogressbar.isShowing()) {
								mSvprogressbar.dismiss();
							}
							finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	private void publishOrder(String shopOrderNumber, String region, String address, String installerTime,
		String publishUserName, String publishUserPhone, String explain) {
		RequestParams params = new RequestParams(HttpURL.PUBLISH_ORDER);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("address", address);
			obj.put("shopOrderNumber", shopOrderNumber);
			obj.put("installerTime", timeStemp);
			obj.put("publishUserName", publishUserName);
			obj.put("publishUserPhone", publishUserPhone);
			obj.put("region", region);
			obj.put("key", "10000");
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			obj.put("requestTime", "" + System.currentTimeMillis());
			Log.i("wmy", "publish Order obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());

		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("wmy", "publish Order 成功=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					int resultCode = jsonObject.optInt("resultCode");
					if (resultCode == 1) {
						getOrder();
					} else {
						if (mSvprogressbar.isShowing()) {
							mSvprogressbar.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), errorMsg);
						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Log.e("Tag", "错误" + ex.getMessage());
				// 清空所有本地数据，进入MainActivity
				ToastShow.Show(getApplicationContext(), getString(R.string.failed));
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {
				Log.e("Tag", "完成");
			}
		});
	}

	private void getOrder() {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_ORDER_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
				Log.d("test", " get all order = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					// Log.e("wmy", "get all order =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");

						if (resultCode.equals("1")) {
							DeviceManager.getInstance().clearOrder();
							DeviceManager.getInstance().getCurrentOrder().setStatus(0);
							JSONArray ja = jsonObject.getJSONArray("data");
							for (int i = 0; i < ja.length(); i++) {
								JSONObject jo = ja.getJSONObject(i);
								String id = jo.getString("id");
								String publishUserId = jo.getString("publishUserId");
								String publishUserName = jo.getString("publishUserName");
								String publishUserPhone = jo.getString("publishUserPhone");
								int createTime = jo.getInt("createTime");
								long installerTime = jo.getLong("installerTime");
								String explain = jo.optString("explain");
								int status = jo.getInt("status");
								String shopOrderNumber = jo.optString("shopOrderNumber");
								double score = jo.getDouble("score");
								String region = jo.getString("region");
								String address = jo.getString("address");
								Order order = new Order(id, publishUserId, publishUserName, publishUserPhone,
										createTime, installerTime, explain, status, score, region, address,
										shopOrderNumber);
								// boolean need = false;
								// if((System.currentTimeMillis()-installerTime)>24*60*60*1000){
								// need = true;
								// }
								if ((status == 8 || status == 2) && score == 0) {
									DeviceManager.getInstance().setCurrentOrder(order);
								}
								DeviceManager.getInstance().addOrder(order);
							}
							if (mSvprogressbar.isShowing()) {
								mSvprogressbar.dismiss();
							}
							ToastShow.Show(getApplicationContext(), "预约成功！");
							Intent intent = new Intent(PublishOrderActivity.this, FirstSetupActivity1.class);
							startActivity(intent);
							finish();

						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							if (mSvprogressbar.isShowing()) {
								mSvprogressbar.dismiss();
							}
							Toast.makeText(getApplicationContext(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
							startActivity(new Intent(getApplicationContext(), LoginActivity.class));
							finish();
						} else {
							if (mSvprogressbar.isShowing()) {
								mSvprogressbar.dismiss();
							}
							finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_publish_order;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mSvprogressbar = new SVProgressHUD(PublishOrderActivity.this);
		mBackL = $(R.id.back_layout);
		tv_statusBar_mian = $(R.id.tv_statusBar_mian);
		mPublishB = $(R.id.public_b);
		mAddressEd = $(R.id.address_ed);
		mContactEd = $(R.id.contact_ed);
		mContactEd1 = $(R.id.contact_ed1);
		mAddrTv = $(R.id.address_tv);
		mDescriptionTv = $(R.id.description_tv);
		dingdanhao_ed = $(R.id.dingdanhao_ed);
		String explain = getIntent().getStringExtra("explain");
		mDescriptionTv.setText(explain);
		mTimeT = $(R.id.time_tv);
		mTimeL = $(R.id.time_l);
		boolVersion();
		mBackL.setOnClickListener(this);
		mTimeL.setOnClickListener(this);
		mPublishB.setOnClickListener(this);
		mAddrTv.setOnClickListener(this);
		String tel = (String) SPUtils.get(getApplicationContext(), "user_name", "");
		mContactEd1.setText(tel);
		dingdanhao_ed.setText(DeviceManager.getInstance().getCurrentOrder().getShopOrderNumber());
		mAddrTv.setText(DeviceManager.getInstance().getCurrentOrder().getRegion());
		mContactEd.setText(DeviceManager.getInstance().getCurrentOrder().getPublishUserName());
		mContactEd1.setText(DeviceManager.getInstance().getCurrentOrder().getPublishUserPhone());
		mAddressEd.setText(DeviceManager.getInstance().getCurrentOrder().getAddress());
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
		timeStemp = DeviceManager.getInstance().getCurrentOrder().getInstallerTime();
		if (timeStemp != 0) {
			String d = simpleDateFormat.format(timeStemp);
			Log.i("wmy", "timeStemp = " + timeStemp + " d = " + d);
			Date date;
			Calendar cal = Calendar.getInstance();
			try {
				date = simpleDateFormat.parse(d);
				cal.setTime(date);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			year = cal.get(Calendar.YEAR) + "";
			month = cal.get(Calendar.MONTH) + "";
			day = cal.get(Calendar.DAY_OF_MONTH) + "";
			hour = cal.get(Calendar.HOUR_OF_DAY) + "";
			mTimeT.setText(year + "年" + month + "月" + day + "日 " + hour + "时");
		}
		String description = getIntent().getStringExtra("explain");
		Log.i(TAG, "description = " + description);
		mDescriptionTv.setText(description);
		if (DeviceManager.getInstance().getCurrentOrder().getPublishUserName() != null) {
			mPublishB.setText("确认修改");
		}
		mAddressEd.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
			}
		});
		initRegion();
	}

	private void initRegion() {
		// TODO Auto-generated method stub
		getProvince();
	}

	private void getProvince() {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				ToastShow.Show(getApplicationContext(), "没有网络");
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_REGION);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("parentCode", 100000);
				obj.put("mid", 1);
				obj.put("key", "10000");
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("type", 1);
				Log.e("wmy", " provinces = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("wmy", "provinces =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							JSONArray jsonArray = jsonObject.getJSONArray("data");
							provinces.clear();
							for (int i = 0; i < jsonArray.length(); i++) {
								JSONObject jo = jsonArray.getJSONObject(i);
								int code = jo.getInt("code");
								int parentCode = jo.getInt("parentCode");
								String name = jo.getString("name");
								String fullName = jo.getString("fullName");
								int type = jo.getInt("type");
								Region province = new Region(name, fullName, code, parentCode, type);
								provinces.add(province);
							}
							if (provinces.size() != 0) {
								getCity(provinces.get(0).getCode());
							}
						} else {
							mAddressEd.setText("暂无地址数据");
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	private void getCity(int parentCode) {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				ToastShow.Show(getApplicationContext(), "没有网络");
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_REGION);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("parentCode", parentCode);
				obj.put("mid", 1);
				obj.put("key", "10000");
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("type", 2);
				Log.e("wmy", " citys = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("wmy", "citys =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							JSONArray jsonArray = jsonObject.getJSONArray("data");
							cities.clear();
							for (int i = 0; i < jsonArray.length(); i++) {
								JSONObject jo = jsonArray.getJSONObject(i);
								int code = jo.getInt("code");
								int parentCode = jo.getInt("parentCode");
								String name = jo.getString("name");
								String fullName = jo.getString("fullName");
								int type = jo.getInt("type");
								Region city = new Region(name, fullName, code, parentCode, type);
								cities.add(city);
							}
							if (cities.size() != 0) {
								getDistricts(cities.get(0).getCode());
							}
							if (dialog != null && dialog.isShowing()) {
								mCityAdapter = new AddressTextAdapter(getApplicationContext(), cities, 0, maxTextSize,
										minTextSize);
								mCityLv.setVisibleItems(4);
								mCityLv.setViewAdapter(mCityAdapter);
								mCityLv.setCurrentItem(0);
								setTextviewSize(cities.get(0).getName(), mCityAdapter);
								cityTv.setText(cities.get(0).getName());
								city = cities.get(0).getName();
							}
						} else {
							mAddressEd.setText("暂无地址数据");
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	private void getDistricts(int parentCode) {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				ToastShow.Show(getApplicationContext(), "没有网络");
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_REGION);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("parentCode", parentCode);
				obj.put("mid", 1);
				obj.put("key", "10000");
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("type", 3);
				Log.e("wmy", " districts = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("wmy", "districts =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							JSONArray jsonArray = jsonObject.getJSONArray("data");
							districts.clear();
							for (int i = 0; i < jsonArray.length(); i++) {
								JSONObject jo = jsonArray.getJSONObject(i);
								int code = jo.getInt("code");
								int parentCode = jo.getInt("parentCode");
								String name = jo.getString("name");
								String fullName = jo.getString("fullName");
								int type = jo.getInt("type");
								Region district = new Region(name, fullName, code, parentCode, type);
								districts.add(district);
							}
							if (dialog != null && dialog.isShowing()) {
								mDistrictAdapter = new AddressTextAdapter(getApplicationContext(), districts, 0,
										maxTextSize, minTextSize);
								mDistLv.setVisibleItems(4);
								mDistLv.setViewAdapter(mDistrictAdapter);
								mDistLv.setCurrentItem(0);
								setTextviewSize(districts.get(0).getName(), mDistrictAdapter);
								districtTv.setText(districts.get(0).getName());
								district = districts.get(0).getName();
							}
						} else {
							mAddressEd.setText("暂无地址数据");
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(LayoutParams.FLAG_TRANSLUCENT_STATUS,
					LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			tv_statusBar_mian.setLayoutParams(layoutParams1);
			tv_statusBar_mian.setVisibility(View.VISIBLE);

		} else {
			tv_statusBar_mian.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// 根据上面发送过去的请求吗来区别
		switch (requestCode) {
		case 0:
			boolean now = intent.getBooleanExtra("now", false);
			Log.i("wmy", "now = " + now);
			boolean cancel = intent.getBooleanExtra("cancel", false);
			if (cancel) {
				return;
			}
			if (!now) {

				String time = "";
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
				String year = intent.getStringExtra("year");
				String month = intent.getStringExtra("month");
				String day = intent.getStringExtra("day");
				String hour = intent.getStringExtra("hour");
				time += year + "-" + month + "-" + day + " " + hour;
				Date date;
				try {
					date = simpleDateFormat.parse(time);
					timeStemp = date.getTime();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// String time = "2017-04-18 22";
				mTimeT.setText(year + "年" + month + "月" + day + "日 " + hour + "时");
			} else {
				mTimeT.setText(getString(R.string.order_now));
				timeStemp = 0;
			}
			break;

		default:
			break;
		}
	}

	private class AddressTextAdapter extends AbstractWheelTextAdapter {
		ArrayList<Region> list;

		protected AddressTextAdapter(Context context, ArrayList<Region> list, int currentItem, int maxsize,
				int minsize) {
			super(context, R.layout.item_region, NO_RESOURCE, currentItem, maxsize, minsize,1);
			this.list = list;
			setItemTextResource(R.id.tempValue);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			View view = super.getItem(index, cachedView, parent);
			return view;
		}

		@Override
		public int getItemsCount() {
			return list.size();
		}

		@Override
		protected CharSequence getItemText(int index) {
			return list.get(index).getName() + "";
		}
	}

	public void setTextviewSize(String curriteItemText, AddressTextAdapter adapter) {
		ArrayList<View> arrayList = adapter.getTestViews();
		int size = arrayList.size();
		String currentText;
		// int currentPosition = 0;
		for (int i = 0; i < size; i++) {
			TextView textvew = (TextView) arrayList.get(i);
			currentText = textvew.getText().toString();
			if (curriteItemText.equals(currentText)) {
				textvew.setTextSize(maxTextSize);
				// currentPosition = i;
				textvew.setTextColor(Color.parseColor("#000000"));
			} else {
				textvew.setTextSize(minTextSize);
				textvew.setTextColor(Color.parseColor("#777777"));
			}
		}
	}

}
